﻿using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using OpenWaves.ActivityFeed.NHibernate;
using OpenWaves.ActivityFeed.Web.Modules;

namespace OpenWaves.ActivityFeed.Web.NHibernate
{
    public abstract class NHibernateActivityFeedBuilder : ActivityFeedBuilder
    {
        protected NHibernateActivityFeedBuilder(IActivityFeedService activityFeedService,
                                             IUpdateDtoBuilder updateDtoBuilder)
            : base(activityFeedService, updateDtoBuilder)
        {
        }

        protected override IQueryable<Update> FilterUpdates(IQueryable<Update> updates)
        {
            return updates.FilterByTopics(this.TopicsFilter);
        }

        protected override IQueryable<Update> SecurityTrimUpdates(IQueryable<Update> updates)
        {
            return updates.SecurityTrim(this.UserGroups);
        }

        [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters")]
        protected override IEnumerable<Update> PaginateUpdates(IQueryable<Update> updates, out PaginationStatus paginationStatus)
        {
            if (this.PaginationRequest == null)
            {
                paginationStatus = PaginationStatus.CompleteResults;
                return updates;
            }

            //
            // Try to get 1 extra update to check if there are more updates
            //            
            var currentPageUpdates = updates.GetPage(this.PaginationRequest.DateFrom, this.PaginationRequest.PageSize + 1).ToList();

            if (currentPageUpdates.Count > this.PaginationRequest.PageSize)
            {
                currentPageUpdates = currentPageUpdates.Take(currentPageUpdates.Count - 1).ToList();
                paginationStatus = PaginationStatus.PartialResults;
            }
            else
            {
                paginationStatus = PaginationStatus.CompleteResults;
            }

            return currentPageUpdates;
        }
    }
}